package cn.com.sd.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.com.sd.common.util.Page;
import cn.com.sd.system.dao.IOrganizationDAO;
import cn.com.sd.system.model.Organization;
import cn.com.sd.system.service.IOrganizationService;

@Component(value = "organizationService")
public class OrganizationServiceImpl implements IOrganizationService{

	@Resource(name = "organizationDAO")
	private IOrganizationDAO organizationDAO;
	
	@Override
	public Integer getOrganizationCount() {
		int count = organizationDAO.getOrganizationCount();
		if (count <= 0) {
			return 0;
		}
		return count;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Organization> list(Page page) {
		
		List<Organization> organizations = new ArrayList<Organization>();
		if (page != null) {
			organizations = organizationDAO.createQuery("from Organization").setFirstResult(page.getStartRow()).setMaxResults(page.getStartRow() + page.getPageSize()).list();
		} else {
			organizations = organizationDAO.createQuery("from Organization").list();
		}
		return organizations;
	}

	@Override
	public Organization detail(Integer id) {
		if (id == null || id <= 0) {
			return null;
		}
		Organization organization = organizationDAO.detail(id);
		if (organization == null) {
			return null;
		}
		return organization;
	}

	@Override
	public Boolean saveOrUpdate(Organization organization) {
		try {
			organizationDAO.saveObject(organization);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	@Override
	public Boolean del(Integer id) {
		try {
			Organization organization = organizationDAO.detail(id);
			if (organization == null) {
				return true;
			}
			
			organizationDAO.deleteObject(organization);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public Boolean delBanch(List<Integer> ids) {
		try {
			List<Organization> organizations = new ArrayList<Organization>();
			for (Integer id : ids) {
				if (id == null || id <= 0) {
					continue;
				}
				Organization temp = new Organization();
				temp.setId(id);
				organizations.add(temp);
			}
			organizationDAO.deleteObjects(organizations);
			return true;
			
		} catch (Exception e) {
			return false;
		}
	}
}
